//对axios进行二次封装
import axios from 'axios'
import { start, done } from 'nprogress' //请求进度

import { getUserToken } from '@/utils/token'

import 'nprogress/nprogress.css' //请求进度条样式

const TEMP_TOKEN_NAME = "TEMP_TOKEN"

const requests = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})
//请求拦截器
requests.interceptors.request.use(
  config => {
    start() //请求进度条开始
    const userToken = getUserToken() //用户的存储本地usertoken 查看是否登录
    if (userToken) {
      config.headers.token = userToken //取到token 发送请求加在请求头headers上
    }
    else {
      const tempToken = localStorage.getItem(TEMP_TOKEN_NAME) //取临时用户的存储本地temptoken
      if (tempToken) {
        config.headers.userTempId = tempToken //取到token 发送请求加在请求头headers上
      }
    }
    return config
  },
  error => Promise.reject(error))

//响应拦截器
requests.interceptors.response.use(
  response => {
    done()// 进度条结束
    if (response.status == 200) {
      return response.data
    }
    return Promise.reject(new Error(response.statusText || 'Error'))
  },
  error => Promise.reject(error))

export default requests;